package com.mico.micochange.server;

import com.alibaba.fastjson.JSONObject;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by chenst on 2018/5/6.
 */
public abstract class MicoPublicThread extends Thread {

    private static final Logger LOG = LoggerFactory.getLogger(MicoPublicThread.class);
    //创建连接对象，作用返回处理结果
    private IoSession session;
    //输入参数
    private String message;

    public MicoPublicThread(IoSession session, String message) {
        this.session = session;
        this.message = message;
    }

    @Override
    public void run() {
        //处理输入参数
        String uuid = UUID.randomUUID().toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        JSONObject json = (JSONObject) JSONObject.parse(message);
        LOG.error(uuid + " input[" + sdf.format(new Date()) + "] @@" + message);

        Map retMap = doDeal(json);
        String retStr = JSONObject.toJSONString(retMap);
        LOG.error(uuid + " out[" + sdf.format(new Date()) + "] ##" + retStr);
        //返回数据
        session.write(retStr);
    }

    /**
     * @param json
     * @return
     */
    public Map doDeal(JSONObject json) {
        Map retMap = new HashMap();
        try {
            retMap = deal(json);
        } catch (Exception ex) {
            ex.printStackTrace();
            String errMsg = "";
            if (ex.getMessage() == null || "".equals(ex.getMessage())) {
                errMsg = "交易失败，请联系外联平台管理员！";
            } else {
                errMsg = ex.getMessage();
            }
            retMap.put("err", errMsg);
        }

        return retMap;
    }

    public abstract Map deal(JSONObject json) throws Exception;

}
